package com.alianzamedica.controllers.drug;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.objectsearch.web.tools.Converter;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Drug;
import com.alianzamedica.tools.Enviroment;
import com.alianzamedica.view.DrugForm;

/**
 * @author Carlos
 * 
 */
public class CreateDrugAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		DrugForm drugForm = (DrugForm) form;
		Drug drug = new Drug();
		String sId = drugForm.getId();
		Integer id = null;
		if (sId != null && sId.trim().length() > 0) {
			id = Integer.valueOf(sId);
			drug.setId(id);
		}
		drug.setName(drugForm.getNombre());
		drug.setBarcode(Converter.string2Integer(drugForm.getCodigo()));
		drug.setDescription(drugForm.getDescripcion());
		drug.setKeywords(drugForm.getKeywords());
		drug.setType(Converter.string2Integer(drugForm.getType()));
		drug.setDose(drugForm.getDosis());
		drug.setDoseTime(drugForm.getTiempo());
		drug.setGenericName(drugForm.getGenericName());
		drug.setNumProduit(Converter.string2Integer(drugForm.getNumProduit()));
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		if (id == null) {
			search.insertObject(drug);
			request.setAttribute("mensaje",
					"se ha agregado al medicamento correctamente");
		} else {
			search.updateObject(drug);
			request.setAttribute("mensaje",
					"se ha actualizado al medicamento correctamente");
		}
		request.setAttribute("linkRetorno", "/admin/drug/list.do");
		return mapping.findForward("success");
	}

}
